#/usr/bin/python
import threading,Queue,sys
import ant
from supplyingant import supplier
from paintingant import painter
from parsingant import parser
from retrievingant import retriever
from functioner import lasthelp,start_daemonic_threads,prepare_argument_list
import time,random,sys
############################################Fetch Data from File##########################################

if(sys.argv[1]=="help"):	lasthelp()
content_of_argument_list=prepare_argument_list(sys.argv)

with open("nopictureavailable.txt",'w') as f:
	clear_file=1
ant.Ant.__commandstring__=sys.argv[1]
if ("g" in sys.argv[1]):
        a=50
if("a" in sys.argv[1]):
        a=5
start_daemonic_threads(a)
for random_placeholder_for_integer in range(len(content_of_argument_list)):
        task=content_of_argument_list.pop(random.randint(0, len(content_of_argument_list)-1)) ###-1 to make it work properly without invoking out of bounds error
        if ".mp3" in task:
		supplier.pile.put(task)
print("Employing "+str(a)+" ant workers")
while True:
        time.sleep(1)
	print(supplier.pile.qsize())
        totalworkersout=ant.Ant.workersout["supplier"]+ant.Ant.workersout["retriever"]+ant.Ant.workersout["painter"]+ant.Ant.workersout["parser"]
        print(ant.Ant.workersout)
        supplier.locallock.acquire()
        supplier.filelock.acquire()
        #print supplier.local
        with open('ref.txt','w') as f:
                pass
        with open('ref.txt','a') as f:
                for k,v in supplier.local.iteritems():
                        if (v!="work" and v!="closed"):
                                try:
                                        f.write(k.encode('utf-8')+"\r"+v.encode('utf-8')+"\n")
                                except:pass
        supplier.locallock.release()
        supplier.filelock.release()
	if((totalworkersout)==0):
                break
